public class ReverseList {

    public static void main(String[] args) {
        ListNode node5 = new ListNode(5);
        ListNode node4 = new ListNode(4, node5);
        ListNode node3 = new ListNode(3, node4);
        ListNode node2 = new ListNode(2, node3);
        ListNode node1 = new ListNode(1, node2);
        ReverseList list = new ReverseList();
        System.out.println(list.reverseKGroup(node1, 3).val);
        

    }
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || k <= 1 ) return head;

        ListNode cur = head;
        int j = k;
        for (int i = k;i > 0;i--){
            if (cur == null) return head;
            cur = cur.next;
        }

        cur = head;

        ListNode prev = head;
        ListNode curr = head.next;
        ListNode next = curr.next;
        int i=k;
        while (--i > 0) {
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        
        head.next = reverseKGroup(curr, k);
        return prev;
    }
}
class ListNode {
    int val;
   ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
